"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RedisClient = void 0;
const Logger_1 = require("./Logger");
const RedisConfig_1 = require("../../config/RedisConfig");
const Config_1 = require("../../config/Config");
const UserModel_1 = require("../../model/UserModel");
const WebServer_1 = require("../../../WebServer");
const redis = require('redis');
class RedisClient {
    init(databaseIndex) {
        this.id = RedisClient.onlyId;
        this.databaseIndex = databaseIndex;
        RedisClient.onlyId++;
        if (!this.isConnected) {
            Logger_1.Logger.log("RedisClient.init", this.id, this.databaseIndex);
            let RDS_OPTS = { auth_pass: Config_1.Config.getRedisPass() };
            this.redisClient = redis.createClient(Config_1.Config.getRedisPort(), Config_1.Config.getRedisUrl(), RDS_OPTS);
            this.redisClient.on('ready', (res) => {
                Logger_1.Logger.log('RedisClient.ready', this.id, this.databaseIndex, res);
            });
            this.redisClient.on('end', (err) => {
                Logger_1.Logger.log('RedisClient.end', this.id, this.databaseIndex, err);
            });
            this.redisClient.on("reconnecting", (err, aa) => {
                Logger_1.Logger.log("RedisClient.reconnecting", err, aa);
            });
            this.redisClient.on('error', (err) => {
                Logger_1.Logger.error("redis connect error==", this.id, this.databaseIndex, err);
                this.isConnected = false;
            });
            this.redisClient.on("warning", (err) => {
                Logger_1.Logger.log("RedisClient.warning", err);
            });
            this.redisClient.monitor((err, res) => {
                if (err) {
                    Logger_1.Logger.error("redis Entering monitoring mode. error", this.databaseIndex, err);
                }
                else {
                    Logger_1.Logger.log("redis Entering monitoring mode.", this.databaseIndex, res);
                }
            });
            this.redisClient.on("monitor", (time, args, rawReply) => {
                // Logger.log("redis data change=1==", time); // 1458910076.446514:['set', 'foo', 'bar']
                // Logger.log("redis data change==2=", args); // 1458910076.446514:['set', 'foo', 'bar']
                // Logger.log("redis data change=3==", rawReply); // 1458910076.446514:['set', 'foo', 'bar']
                // "1596442771.252363 [0 113.111.247.226:52493] "select" "15""
                let rawArr = rawReply.split(" ");
                let nowDatabaseIndex = parseInt(rawArr[1].substring(1));
                let cmd = String(args[0]).toLowerCase();
                // Logger.log("redis cmd======rawArr=", cmd, rawArr, rawArr[1][1], nowDatabaseIndex)
                // Logger.log("redis cmd===",cmd, rawArr[1], nowDatabaseIndex)
                // if (cmd == "set" || cmd == "del" || cmd == "HMSET") {
                if (cmd == "set" || cmd == "del" || cmd == "hmset") {
                }
            });
            this.redisClient.on("connect", (param) => {
                Logger_1.Logger.log("redis connect suc==", this.id, this.databaseIndex, param);
                this.isConnected = true;
                this.selectDatabase(this.databaseIndex + "", () => {
                    if (this.databaseIndex == RedisConfig_1.RedisConfig.Database_Index.Users) {
                        if (Config_1.Config.serverType == Config_1.Config.ServerType_List.LoginServer || Config_1.Config.serverType == Config_1.Config.ServerType_List.GameServer) {
                            UserModel_1.UserModel.initOnlyId();
                        }
                        if (Config_1.Config.serverType == Config_1.Config.ServerType_List.WebServer) {
                            WebServer_1.WebServer.instance.initServerList();
                        }
                    }
                });
            });
        }
    }
    selectDatabase(databaseName = "1", callback) {
        if (this.isGettingData || this.isGettingKeys) { //正在获取数据获取获取Keys不能切换数据库
            callback && callback(false);
        }
        else if (this.nowSelectingDatabase) { //正在切换数据库
            callback && callback(false);
        }
        else if (this.nowSelectDatabase == databaseName) {
            callback && callback(true);
        }
        else {
            this.nowSelectingDatabase = databaseName;
            Logger_1.Logger.log("selectDatabase==start", databaseName);
            this.redisClient.select(databaseName, (err) => {
                this.nowSelectingDatabase = null;
                this.nowSelectDatabase = databaseName;
                if (err) {
                    Logger_1.Logger.error('RedisClient selectDatabase error', err);
                }
                else {
                    Logger_1.Logger.log("selectDatabase==suc", databaseName);
                    callback && callback(true);
                }
            });
        }
    }
    getAllKeys(callback) {
        this.redisClient.keys("*", (err, keyList) => {
            if (err) {
                Logger_1.Logger.error("getAllKeys error", this.databaseIndex, err);
            }
            else {
                this.isGettingKeys = false;
                callback && callback(true, keyList);
            }
        });
    }
    getKeysPromise(keys) {
        return new Promise((resolve, reject) => {
            this.getKeys(keys, (isOk, keyList) => {
                resolve(keyList);
            });
        });
    }
    getKeys(keys, callback) {
        this.redisClient.keys(keys, (err, keyList) => {
            this.isGettingKeys = false;
            if (err) {
                Logger_1.Logger.error("RedisClient getKeys error==", keys, err);
            }
            else {
                callback && callback(true, keyList);
            }
        });
        // }
    }
    getValuePromise(key = "100001") {
        return new Promise((resolve, reject) => {
            this.getValue(key, (obj) => {
                resolve(obj);
            });
        });
    }
    getValue(key = "100001", callback = null) {
        this.isGettingData = true;
        this.redisClient.get(key, (err, data) => {
            this.isGettingData = false;
            if (err) {
                Logger_1.Logger.error("RedisClient getValue error==", key, err);
            }
            else {
                Logger_1.Logger.log("RedisClient getValue===", key, data);
                callback && callback(data);
            }
        });
    }
    setValue(key, value, callback = null) {
        this.redisClient.set(key, value, (err, data) => {
            if (err) {
                Logger_1.Logger.error("RedisClient setValue error==", key, err);
            }
            else {
                // Logger.log("RedisClient setValue===", key, value, data);
                callback && callback(true, data);
            }
        });
    }
    zrange(key, callback) {
        this.redisClient.zrange(key, 0, -1, (err, res) => {
            if (err != null) {
                Logger_1.Logger.log("==zrange== error is: ", err);
            }
            else {
                Logger_1.Logger.log("zrange===data==", res);
                callback && callback(res);
            }
        });
    }
    //设置过期时间
    expire(key, second) {
        this.redisClient.expire(key, second); //60秒自动过期
    }
    hlenPromise(key) {
        return new Promise((resolve, reject) => {
            this.hlen(key, (obj) => {
                resolve(obj);
            });
        });
    }
    hlen(key, callback) {
        this.redisClient.hlen(key, (err, obj) => {
            if (err) {
                Logger_1.Logger.error("hlen error===", key);
            }
            else {
                callback && callback(obj);
            }
        });
    }
    hsetPromise(key1, key2, value) {
        return new Promise((resolve, reject) => {
            this.hset(key1, key2, value, (obj) => {
                resolve(obj);
            });
        });
    }
    hset(key1, key2, value, callback) {
        this.redisClient.hset(key1, key2, value, (err, obj) => {
            if (err) {
                Logger_1.Logger.error("hset error===", key1, key2);
            }
            else {
                callback && callback(obj);
            }
        });
    }
    hgetPromise(key1, key2) {
        return new Promise((resolve, reject) => {
            this.hget(key1, key2, (obj) => {
                resolve(obj);
            });
        });
    }
    hget(key, key2, callback) {
        this.redisClient.hget(key, key2, (err, obj) => {
            if (err) {
                Logger_1.Logger.error("hget error===", key, key2);
            }
            else {
                // Logger.log("hget obj=====", obj)
                callback && callback(obj);
            }
        });
    }
    hgetallPromise(key) {
        return new Promise((resolve, reject) => {
            this.hgetall(key, (data) => {
                resolve(data);
            });
        });
    }
    hgetall(key, callback) {
        this.redisClient.hgetall(key, (err, obj) => {
            if (err) {
                Logger_1.Logger.error("hgetall error====", err);
            }
            else {
                Logger_1.Logger.log("hgetall obj=====", obj);
                callback && callback(obj);
            }
        });
    }
    testZset() {
        //按照 Score1,Key1,Score2,Key2,Score3,Key3方式初始化的
        var vals = [13, 1, 12, 2, 14, 3, 20, 4];
        // Logger.log("testZset=== 111=", vals)
        // this.redisClient.zadd('mysort', vals, (err, res) => {
        //     if (err != null) {
        //         Logger.log("testZset=== zadd=error", err)
        //     } else {
        //         // Logger.log(res);
        //         Logger.log("testZset=== zadd=11111111", res)
        //     }
        // });
        // // //无穷大和无穷小的分数区间内，key排名情况
        this.redisClient.zrange('mysort', 0, -1, (err, res) => {
            if (err != null) {
                Logger_1.Logger.log("==zrange== error is: ", err);
            }
            else {
                Logger_1.Logger.log("zrange===data==", res);
            }
        });
        //无穷大和无穷小的分数区间内，排名总数
        // this.redisClient.zcount('mysort', -Infinity, Infinity, (err, res) => {
        //     if (err != null) {
        //         Logger.log("==zcount== error is: ", err);
        //     } else {
        //         Logger.log("zcount=====", res);
        //     }
        // });
        // //无穷大和无穷小的分数区间内，从大到小的排序
        // let args1 = ['mysort', '+inf', '-inf'];
        // this.redisClient.zrevrangebyscore(args1,  (err, res)=> {
        //     if (err != null) {
        //         Logger.log("==zrevrangebyscore== error is: ", err);
        //     } else {
        //         Logger.log("zrevrangebyscore===",res);
        //     }
        // });
        //指定分数区间，指定查询数量，偏移指定位数后的排名
        // let max = 3, min = 1, offset = 0, count = 3;
        // var max = 25, min = 1, offset = 0, count = 4;
        // let args2 = ['mysort', max, min, 'WITHSCORES', 'LIMIT', offset, count];
        // this.redisClient.zrevrangebyscore(args2,  (err, res) =>{
        //     if (err != null) {
        //         Logger.log("==zrevrangebyscore== error is: ", err);
        //     } else {
        //         Logger.log("zrevrangebyscore===",res);
        //     }
        // });
        //根据key去对应排名，从大到小，排名从0开始所以+1
        // let args3 = ['mysort', 4]
        // let args3 = ['mysort', 3]
        // this.redisClient.zrevrank(args3, (err, res) => {
        //     if (err != null) {
        //         Logger.log("==zrevrank== error is: ", err);
        //     } else {
        //         Logger.log("zrevrank===", res);
        //     }
        // });
    }
}
exports.RedisClient = RedisClient;
RedisClient.onlyId = 0;
